package org.jeecg.modules.cascv.image.service.merge.liutigui;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.HexUtil;
import cn.hutool.core.util.RandomUtil;
import com.NativeImageIO;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import lombok.extern.slf4j.Slf4j;
import org.checkerframework.checker.units.qual.A;
import org.jeecg.common.api.vo.Result;
import org.jeecg.config.TaskExecutePool;
import org.jeecg.modules.cascv.image.service.merge.ImageService;
import org.jeecg.modules.cascv.image.util.BayerUtil;
import org.jeecg.modules.cascv.image.util.LaptopConstant;
import org.jeecg.modules.cascv.image.util.LaptopUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Base64;
import java.util.List;
import java.util.TreeSet;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * @author贺弘烨
 * @Version 2022/3/21
 * description;
 * TGMTYY1301_06BH_31_FPRAPP23
 */
@Service

@Slf4j
public class LiutiguiApp23Service extends ImageService {
    @Value("${imageurl}")
    private  String imageurl;
    @Autowired
    private TaskExecutePool taskExecutePool;
    public static String frames_field = "A1_FPR_MICU_APP23DATA_44_2021_1";
    public static String imageNum_field = "A1_FPR_MICU_APP23DATA_23_26_1";
    public static String width_field = "A1_FPR_MICU_APP23DATA_33_34_1";
    public static String height_field = "A1_FPR_MICU_APP23DATA_35_36_1";

    @Override
    public String idsNames() {
        return "TGMTYY1301_06BH_31_FPRAPP23,6D2BH_2FH,6D2BH_2FH_UDP";
    }

    @Override
    public Result<Object> merge(JSONObject jsonObject, String idsName, String key) {
        JSONObject conJson = jsonObject.getJSONObject("Content");

        //打印报错不连续的包序号
        String packageNum = conJson.getString(LaptopConstant.Package_number_MAP.get(idsName));
        int intpackageNum = Integer.parseInt(packageNum.split(";")[1]);
        Integer lastPackageNum = LaptopConstant.packageNumMap.get(key);

        if(null==lastPackageNum){
            LaptopConstant.packageNumMap.put(key,intpackageNum);
        }else {
            LaptopConstant.packageNumMap.put(key,intpackageNum);
            if (lastPackageNum + 1 != intpackageNum) {
                if (2511 != lastPackageNum && 0 != intpackageNum) {
                    log.error("图像丢包，包序号不连续，当前包的包序号:"+intpackageNum+"，上一包包序号:"+lastPackageNum);
                }
            }
        }

        String secondStr = jsonObject.getString("second");
        long second = Long.parseLong(secondStr);
        String subSecondStr = jsonObject.getString("subsecond");
        secondStr = LaptopUtil.toDayHoursMinSec(second);
        String nextImageNum = conJson.getString(imageNum_field);
        String dataFrames = conJson.getString(frames_field);
        nextImageNum = nextImageNum.split(";")[0];
        dataFrames = dataFrames.split(";")[1].substring(2).trim();
        //dataFrames = dataFrames.substring(7,dataFrames.length()-10);
        StringBuilder queue = LaptopConstant.imageData.get(key);

        composite(idsName, key, conJson, dataFrames, queue, nextImageNum,secondStr,subSecondStr);
        return null;
    }


    //TGMTYY1301_06BH_31_FPRAPP1
    public  boolean composite(String idsName, String key, JSONObject content, String dataFrames, StringBuilder queue, String currImageNum,String secondStr,String subSecondStr) {


        String lastImageNum = LaptopConstant.imageNumMap.get(key);

        //获取宽度
        int width = Integer.parseInt((content.getString(width_field)).split(";")[1]);
        //获取高度
        int height = Integer.parseInt((content.getString(height_field)).split(";")[1]);

        //System.out.println("imageNum=" + lastImageNum);
        //System.out.println("nextImageNum=" + currImageNum);

        if (lastImageNum == null || lastImageNum.equals(currImageNum)) {
            if (queue != null) {
                queue.append(dataFrames);
                LaptopConstant.imageData.put(key, queue);
            } else {
                queue = new StringBuilder();
                LaptopConstant.imageData.put(key, queue);
                queue.append(dataFrames);
            }
        } else {

            String imgHexStr = LaptopConstant.imageData.get(key).toString();

            if (imgHexStr.length()/2 >= width * height) {
                CompletableFuture<JSONObject> future = CompletableFuture.supplyAsync(() -> {
                    long start = System.currentTimeMillis();
                    //      byte[] array = HexUtil.decodeHex(imgHexStr);
                    int[] intArr = bayer12(imgHexStr);

                    int[] bayerArr = BayerUtil.bayer2RGB_GB_3(intArr, width, height);
                    byte[] arr = new byte[bayerArr.length];
                    for (int i = 0; i < bayerArr.length; i++) {
                        arr[i] = (byte) do12to8(bayerArr[i]);
                    }
//
//                        int[] bgrArray = new int[array.length / 2];
//                        TreeSet<Integer> bgrSet = new TreeSet<>();
//                        for (int i = 0; i < array.length; i++) {
//                            byte aByte = array[i];
//                            i = i + 1;
//                            byte bByte = array[i];
//                            int a = aByte & 0xff;
//                            int b = bByte & 0xff;
//                            int v = b << 8 | a;
//
//                            bgrArray[i/2] = v;
//                            bgrSet.add(v);
//                        }
//                        int max = 0;
//                        int min = 0;
//                        if(bgrSet.size() > 20){
//                            for (int i = 0; i < 10; i++) {
//                                max = bgrSet.pollLast();
//                            }
//                            for (int i = 0; i < 10; i++) {
//                                min = bgrSet.pollFirst();
//                            }
//                        }else{
//                            max = bgrSet.pollLast();
//                            min = bgrSet.pollFirst();
//                        }
//                        int[] newArray = new int[bgrArray.length];
//                        int cha = max - min;
//                        for (int i = 0; i < bgrArray.length; i++) {
//                            int v = bgrArray[i];
//                            if(v > max){
//                                v = max;
//                            }else if(v < min){
//                                v = min;
//                            }
//                            newArray[i] = (byte) ((v - min) * 255 / cha);
//                        }
//                        int[] bayerArr = BayerUtil.bayer2RGB_BG(newArray, width, height);
//                        byte[] arr = new byte[bayerArr.length];
//                        for (int i = 0; i < bayerArr.length; i++) {
//                            arr[i] = (byte) bayerArr[i];
//                        }

                        String idStr = IdWorker.getIdStr();
                        int png = LaptopConstant.nativeImageIO.write2BGRAndScale(arr, height, width, "/data/images/", idStr + ".png", "png",0.1d);
                        String imageUrl = "http://"+imageurl+"/jeecg-boot/test/gmvVideo/getImage/"+idStr+".png";
                        content.put("imageUrl",imageUrl);
                        content.put("idsName", idsName);
                        String[] split = secondStr.split(":");
                        content.put("ts", split[0] + "天" + split[1] + "时" + split[2] + "分" + split[3] + "秒" + subSecondStr + "微秒");
                        content.remove(LaptopConstant.FRAME_FIELD_MAP.get(idsName));
                    content.put("key", key);
                    log.info("流体柜6D2BH_2FH, 合成一张图片消耗时间：" + (System.currentTimeMillis() - start) + "毫秒");

                    return content;
                },taskExecutePool.threadPoolTaskExecutor2());
                LaptopConstant.imageFutureList.add(future);

            }
            queue = new StringBuilder();
            queue.append(dataFrames);
            LaptopConstant.imageData.put(key, queue);
        }
        LaptopConstant.imageNumMap.put(key, currImageNum);
        return true;
    }

    private  int do12to8(int a) {
        double aa = a * 1.0;
        double bb = aa / 4095.0;
        aa = bb * 255.0;
        a = new Double(aa).intValue();
        return a;
    }

    private  int[] bayer12(String a) {
        if (a == null) {
            return null;
        }
        List<Integer> list = new ArrayList<>();
        for (int i = 0; i + 4 <= a.length(); i = i + 4) {
            String partStr = a.substring(i, i + 4);
            char[] aChararr = partStr.toCharArray();
            StringBuilder sb1 = new StringBuilder();
            sb1.append(aChararr[2]);
            sb1.append(aChararr[3]);
            sb1.append(aChararr[0]);
            sb1.append(aChararr[1]);
            list.add(Integer.parseInt(sb1.toString(), 16));
        }
        if (list.size() == 0) {
            return null;
        }
        int[] ints = new int[list.size()];
        for (int i = 0; i < list.size(); i++) {
            int b = list.get(i);
            ints[i] = b;
        }
        return ints;
    }

    public static void main(String[] args) {
        System.load("D:/disk1/libjpeg-9.dll");
        System.load("D:/disk1/libpng-3.dll");
        System.load("D:/disk1/NativeImageIOJNI.dll");
        List<String> strings = FileUtil.readUtf8Lines("D:\\pc_workspace\\TGMTYY1301_06BH_31_FPRAPP23.txt");
        LiutiguiApp23Service liutiguiApp23Service = new LiutiguiApp23Service();

        for (String string : strings) {
            //将str转化为相应的JSONObject对象
            JSONObject jsonObject = JSONObject.parseObject(string);
            liutiguiApp23Service.merge(jsonObject, "TGMTYY1301_06BH_31_FPRAPP23", "TGMTYY1301_06BH_31_FPRAPP23");
        }

    }


}
